home *** CD-ROM | disk | FTP | other *** search
/ Mac Easy 2010 May / Mac Life Ubuntu.iso / casper / filesystem.squashfs / usr / share / transmission / web / javascript / common.js next >
Encoding:
JavaScript  |  2009-03-30  |  9.1 KB  |  346 lines

  1. /*
  2.  *    Copyright ¬© Dave Perrett and Malcolm Jarvis
  3.  *    This code is licensed under the GPL version 2.
  4.  *    For more details, see http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
  5.  *
  6.  * Common javascript
  7.  */
  8.  
  9. var transmission;
  10. var dialog;
  11. // Test for a Webkit build that supports box-shadow: 521+ (release Safari 3 is
  12. // actually 523.10.3). We need 3.1 for CSS animation (dialog sheets) but as it
  13. // degrades gracefully let's not worry too much.
  14. var Safari3 = testSafari3();
  15. var iPhone = RegExp("(iPhone|iPod)").test(navigator.userAgent);
  16. if (iPhone) var scroll_timeout;
  17.  
  18. function testSafari3()
  19. {
  20.     var minimum = new Array(521,0);
  21.     var webKitFields = RegExp("( AppleWebKit/)([^ ]+)").exec(navigator.userAgent);
  22.     if (!webKitFields || webKitFields.length < 3) return false;
  23.     var version = webKitFields[2].split(".");
  24.     for (var i = 0; i < minimum.length; i++) {
  25.         var toInt = parseInt(version[i]);
  26.         var versionField = isNaN(toInt) ? 0 : toInt;
  27.         var minimumField = minimum[i];
  28.         
  29.         if (versionField > minimumField) return true;
  30.         if (versionField < minimumField) return false;
  31.     }
  32.     return true;
  33. };
  34.  
  35. $(document).ready( function() {
  36.     // Initialise a torrent controller to handle events
  37.     
  38.     // Initialise the dialog controller
  39.     dialog = new Dialog();
  40.     
  41.     // Initialise the main Transmission controller
  42.     transmission = new Transmission();
  43.  
  44.     if ($.browser.safari) {
  45.         
  46.         // Fix div height problem - causes scrollbar flash in
  47.         // firefox so have to be safari-specific
  48.         $('#torrent_inspector').css('height', '100%');
  49.         
  50.         // Move search field's margin down for the styled input
  51.         $('#torrent_search').css('margin-top', 3);        
  52.     }
  53.     if (!Safari3 && !iPhone) {
  54.         // Fix for non-Safari-3 browsers: dark borders to replace shadows.
  55.         // Opera messes up the menu if we use a border on .trans_menu
  56.         // div.outerbox so use ul instead
  57.         $('.trans_menu ul, div#jqContextMenu, div.dialog_container div.dialog_window').css('border', '1px solid #777');
  58.         // and this kills the border we used to have
  59.         $('.trans_menu div.outerbox').css('border', 'none');
  60.     } else if (!iPhone) {
  61.         // Used for Safari 3.1 CSS animation. Degrades gracefully (so Safari 3
  62.         // test is good enough) but we delay our hide/unhide to wait for the
  63.         // scrolling - no point making other browsers wait.
  64.         $('div#upload_container div.dialog_window').css('top', '-205px');
  65.         $('div#prefs_container div.dialog_window').css('top', '-425px');
  66.         $('div#dialog_container div.dialog_window').css('top', '-425px');
  67.         $('div.dialog_container div.dialog_window').css('-webkit-transition', 'top 0.3s');
  68.         // -webkit-appearance makes some links into buttons, but needs
  69.         // different padding.
  70.         $('div.dialog_container div.dialog_window a').css('padding', '2px 10px 3px');
  71.     }
  72.     if (iPhone)
  73.         if(window.navigator.standalone)
  74.             // Fix min height for iPhone when run in full screen mode from home screen
  75.             // so the footer appears in the right place
  76.             $('body div#torrent_container').css('min-height', '338px');
  77. });
  78.  
  79. /*
  80.  *   Return a copy of the array
  81.  *
  82.  *   @returns array
  83.  */
  84. Array.prototype.clone = function () {
  85.     return this.concat();
  86. };
  87.  
  88. /**
  89.  * "innerHTML = html" is pretty slow in FF.  Happily a lot of our innerHTML
  90.  * changes are triggered by periodic refreshes on torrents whose state hasn't
  91.  * changed sine the last update, so even this simple test helps a lot.
  92.  */
  93. function setInnerHTML( e, html )
  94. {
  95.     if( e.innerHTML != html )
  96.         e.innerHTML = html;
  97. };
  98.  
  99. /*
  100.  *   Converts file & folder byte size values to more  
  101.  *   readable values (bytes, KB, MB, GB or TB).
  102.  *
  103.  *   @param integer bytes
  104.  *   @returns string
  105.  */
  106. Math.formatBytes = function(bytes) {
  107.     var size;
  108.     var unit;
  109.     
  110.     // Terabytes (TB).
  111.     if ( bytes >= 1099511627776 ) { 
  112.         size = bytes / 1099511627776;
  113.         unit = ' TB'; 
  114.     
  115.     // Gigabytes (GB).
  116.     } else if ( bytes >= 1073741824 ) { 
  117.         size = bytes / 1073741824;
  118.         unit = ' GB';
  119.  
  120.     // Megabytes (MB).
  121.     } else if ( bytes >= 1048576 ) { 
  122.         size = bytes / 1048576;
  123.         unit = ' MB';
  124.  
  125.     // Kilobytes (KB).
  126.     } else if ( bytes >= 1024 ) { 
  127.         size = bytes / 1024;
  128.         unit = ' KB';
  129.  
  130.     // The file is less than one KB
  131.     } else {
  132.         size = bytes;
  133.         unit = ' bytes';
  134.     }
  135.     
  136.     // Single-digit numbers have greater precision
  137.     var precision = 1; 
  138.     if (size < 10) {
  139.         precision = 2;
  140.     }
  141.     size = Math.roundWithPrecision(size, precision);
  142.     
  143.     // Add the decimal if this is an integer
  144.     if ((size % 1) == 0 && unit != ' bytes') {
  145.         size = size + '.0';
  146.     }
  147.  
  148.     return size + unit;
  149. };
  150.  
  151.  
  152. /*
  153.  *   Converts seconds to more readable units (hours, minutes etc).
  154.  *
  155.  *   @param integer seconds
  156.  *   @returns string
  157.  */
  158. Math.formatSeconds = function(seconds)
  159. {
  160.     var result;
  161.     var days = Math.floor(seconds / 86400);
  162.     var hours = Math.floor((seconds % 86400) / 3600);
  163.     var minutes = Math.floor((seconds % 3600) / 60);
  164.     var seconds = Math.floor((seconds % 3600) % 60);    
  165.  
  166.     if (days > 0 && hours == 0)
  167.         result = days + ' days';
  168.     else if (days > 0 && hours > 0)
  169.         result = days + ' days ' + hours + ' hr';
  170.     else if (hours > 0 && minutes == 0)
  171.         result = hours + ' hr';   
  172.     else if (hours > 0 && minutes > 0)
  173.         result = hours + ' hr ' + minutes + ' min';
  174.     else if (minutes > 0 && seconds == 0)
  175.         result = minutes + ' min';
  176.     else if (minutes > 0 && seconds > 0)
  177.         result = minutes + ' min ' + seconds + ' seconds';
  178.     else
  179.         result = seconds + ' seconds';  
  180.  
  181.     return result;
  182. };
  183.  
  184.  
  185. /*
  186.  *   Converts a unix timestamp to a human readable value
  187.  *
  188.  *   @param integer seconds
  189.  *   @returns string
  190.  */
  191. Math.formatTimestamp = function(seconds) {
  192.     var myDate = new Date(seconds*1000);
  193.     return myDate.toGMTString();
  194. };
  195.  
  196. /*
  197.  *   Round a float to a specified number of decimal 
  198.  *   places, stripping trailing zeroes
  199.  *
  200.  *   @param float floatnum
  201.  *   @param integer precision
  202.  *   @returns float
  203.  */
  204. Math.roundWithPrecision = function(floatnum, precision) {
  205.     return Math.round ( floatnum * Math.pow ( 10, precision ) ) / Math.pow ( 10, precision );
  206. };
  207.  
  208.  
  209. /*
  210.  *   Given a numerator and denominator, return a ratio string
  211.  */
  212. Math.ratio = function( numerator, denominator )
  213. {
  214.     var result = Math.roundWithPrecision((numerator / denominator), 2);
  215.  
  216.     // check for special cases
  217.     if (isNaN(result)) result = 0;
  218.     if (result=="Infinity") result = "∞";
  219.  
  220.     // Add the decimals if this is an integer
  221.     if ((result % 1) == 0)
  222.         result = result + '.00';
  223.  
  224.     return result;
  225. };
  226.  
  227. /*
  228.  * Trim whitespace from a string
  229.  */
  230. String.prototype.trim = function () {
  231.     return this.replace(/^\s*/, "").replace(/\s*$/, "");
  232. }
  233.  
  234. /**
  235.  * @brief strcmp()-style compare useful for sorting
  236.  */
  237. String.prototype.compareTo = function( that ) {
  238.     // FIXME: how to fold these two comparisons together?
  239.         if( this < that ) return -1;
  240.         if( this > that ) return 1;
  241.         return 0;
  242. }
  243.  
  244.  
  245. /***
  246. ****  Preferences
  247. ***/
  248.  
  249. function Prefs() { }
  250. Prefs.prototype = { };
  251.  
  252. Prefs._AutoStart          = 'auto-start-torrents';
  253.  
  254. Prefs._RefreshRate        = 'refresh_rate';
  255.  
  256. Prefs._ShowFilter         = 'show_filter';
  257.  
  258. Prefs._ShowInspector      = 'show_inspector';
  259.  
  260. Prefs._FilterMode         = 'filter';
  261. Prefs._FilterAll          = 'all';
  262. Prefs._FilterSeeding      = 'seeding';
  263. Prefs._FilterDownloading  = 'downloading';
  264. Prefs._FilterPaused       = 'paused';
  265.  
  266. Prefs._SortDirection      = 'sort_direction';
  267. Prefs._SortAscending      = 'ascending';
  268. Prefs._SortDescending     = 'descending';
  269.  
  270. Prefs._SortMethod         = 'sort_method';
  271. Prefs._SortByAge          = 'age';
  272. Prefs._SortByActivity     = 'activity';
  273. Prefs._SortByQueue        = 'queue_order';
  274. Prefs._SortByName         = 'name';
  275. Prefs._SortByProgress     = 'percent_completed';
  276. Prefs._SortByState        = 'state';
  277. Prefs._SortByTracker      = 'tracker';
  278.  
  279.  
  280. Prefs._Defaults =
  281. {
  282.     'auto-start-torrents': true,
  283.     'filter': 'all',
  284.     'refresh_rate' : 5,
  285.     'show_filter': true,
  286.     'show_inspector': false,
  287.     'sort_direction': 'ascending',
  288.     'sort_method': 'name'
  289. };
  290.  
  291. /*
  292.  * Set a preference option
  293.  */
  294. Prefs.setValue = function( key, val )
  295. {
  296.     if( Prefs._Defaults[key] == undefined )
  297.         console.warn( "unrecognized preference key '%s'", key );
  298.  
  299.     var days = 30;
  300.     var date = new Date();
  301.     date.setTime(date.getTime()+(days*24*60*60*1000));
  302.     document.cookie = key+"="+val+"; expires="+date.toGMTString()+"; path=/";
  303. };
  304.  
  305. /**
  306.  * Get a preference option
  307.  *
  308.  * @param key the preference's key
  309.  * @param fallback if the option isn't set, return this instead
  310.  */
  311. Prefs.getValue = function( key, fallback )
  312. {
  313.     var val;
  314.  
  315.     if( Prefs._Defaults[key] == undefined )
  316.         console.warn( "unrecognized preference key '%s'", key );
  317.  
  318.         var lines = document.cookie.split( ';' );
  319.         for( var i=0, len=lines.length; !val && i<len; ++i ) {
  320.         var line = lines[i].trim( );
  321.         var delim = line.indexOf( '=' );
  322.         if( ( delim == key.length ) && line.indexOf( key ) == 0 )
  323.             val = line.substring( delim + 1 );
  324.     }
  325.  
  326.     // FIXME: we support strings and booleans... add number support too?
  327.     if( !val ) val = fallback;
  328.     else if( val == 'true' ) val = true;
  329.     else if( val == 'false' ) val = false;
  330.     return val;
  331. };
  332.  
  333. /**
  334.  * Get an object with all the Clutch preferences set
  335.  *
  336.  * @pararm o object to be populated (optional)
  337.  */
  338. Prefs.getClutchPrefs = function( o )
  339. {
  340.     if( !o )
  341.         o = { };
  342.     for( var key in Prefs._Defaults )
  343.         o[key] = Prefs.getValue( key, Prefs._Defaults[key] );
  344.     return o;
  345. };
  346.